package com.tvb.comm.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.tvb.pojo.LoginUser;
import com.tvb.service.UserRoleService;
/**
 * @author stan
 *
 */
//2
public class MyUserDetailServiceImpl implements UserDetailsService {
	@Autowired
	private UserRoleService userRoleService;
	
	//登录验证
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//这里应该可以不用再查了
		LoginUser user = null;
		try {
			user = userRoleService.findByName(username);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(user == null)throw new AuthenticationServiceException("用户名无效！");
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);
		
		boolean enables = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		//封装成spring security的user
		User userdetail = new User(user.getName(), user.getPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
		
		return userdetail;
	}
	
	//取得用户的权限
	private Set<GrantedAuthority> obtionGrantedAuthorities(LoginUser user) {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		Iterator<Integer> roles = user.getRoleCodes().iterator();
		while (roles.hasNext()) {
			authSet.add(new GrantedAuthorityImpl(String.valueOf(roles.next())));
		}
		//authSet.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
		//authSet.add(new GrantedAuthorityImpl("ROLE_USER"));
		return authSet;
	}
}
